// pages/shopping/shopping.js

import request from "../../utils/request.js"

import storage from "../../utils/storage.js"

Page({


    // 点进按钮开启扫码
    async handleClick(){
        let {result} = await this.scanCodePromise();
        if(!result){
            return
        }
        let res = await request('/api/getProduct', {qcode: result});
        if(res.success === true && res.result.length > 0){
            this.addCart(res.result[0]);
            wx.navigateTo({
                url: '/pages/cart/cart',
              })
        }
    },

    addCart(data){
        let carts = storage.get("carts") || [];

        let index = carts.findIndex((item, index) => {
            return item._id == data._id
        })
        // console.log(index)

        if(index === -1){
            data.num = 1;
            carts.push(data)
            storage.set("carts", carts)
        }else{
            let item = carts.find((item) => {
                if(item._id === data._id){
                    return item
                }   
            })
            item.num++;
            carts.forEach(i => {
                if(i._id === item._id){
                    i = item[0]
                }
            })
            storage.set("carts", carts)
        }
    },
 
    scanCodePromise(){
        return new Promise((resolve, reject) => {
            wx.scanCode({
                success: (res) => {
                    resolve(res)
                },
                fail: (err) => {
                    reject(err)
                },
              })
        })
    },

    /**
     * 页面的初始数据
     */
    data: {
        avatar: [
            {
                id: 1,
                url: 'https://img.alicdn.com/simba/img/TB15tIjGVXXXXcoapXXSutbFXXX.jpg'
            },
            {
                id: 2,
                url: 'https://img.alicdn.com/imgextra/i2/6000000000023/O1CN01fVAS4O1C2Zq0D1FCo_!!6000000000023-0-lubanimage.jpg'
            },
            {
                id: 3,
                url: 'https://img.alicdn.com/imgextra/i2/67/O1CN01W0447S1CMjGbrljsw_!!67-0-luban.jpg'
            },
        ]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})